<template>
	<view>
		<u-navbar :border-bottom="false"></u-navbar>
		<view class="body">
			<view class="title">
				<view class="u-font-60 text-bold">密码登录</view>
				<view class="text-gray u-m-t-20 u-font-28" >欢迎登录司空密信</view>
			</view>
			<view>
				<view class="phone-row u-flex">
					<view class="u-flex u-m-r-30 u-font-36" @tap="areaPicker.show=true">
						<text class="" style="font-size: 32rpx;">+</text><!-- ﹢ -->
						<text class="" style="padding-right:15rpx;">{{areaCode}}</text>
						<u-icon name="arrow-down" color="#666" size="26"></u-icon>
					</view>
					<input class="u-font-40" maxlength="20" type="number" v-model="phone" placeholder="请输入手机号" @blur="checkPhone" />
				</view>
				<view class="tips" :class="{error:phoneStatus.error}">{{phoneStatus.des}}</view>
			</view>
			<view>
				<view class="u-flex">
					<input class="input u-flex-1" type="password" v-model="password" placeholder="请输入登录密码" @blur="checkPwd"/>
				</view>
				<view class="tips" :class="{error:pwdStatus.error}">{{pwdStatus.des}}</view>
			</view>
			<view>
				<view class="u-flex">
					<input class="input u-flex-1" maxlength="11" type="text" v-model="captcha.code"
						placeholder="请输入图形码" @blur="checkCaptcha"/>
					<view @tap="getCaptcha" class="img-code u-m-l-20"
						:style="`background-image: url(data:image/png;base64,${captcha.base64})`"></view>
				</view>
				<view class="tips" :class="{error:imgStatus.error}">{{imgStatus.des}}</view>
			</view>
			<!-- disable -->
			<view class="submit" @tap="submit">立即登录</view>
		</view>
		<view class="u-flex u-row-center u-m-t-50">
			<u-checkbox v-model="agree" shape="circle">
				<text class="text-gray u-font-26">
					登录即表明同意
					<text class="text-blue" @tap.stop="jumpTo('/pages/agreement/agreement?id=shiyong')">《用户使用协议》</text>
					和
					<text class="text-blue" @tap.stop="jumpTo('/pages/agreement/agreement?id=yinsixieyi')">《隐私条款》</text>
				</text>
			</u-checkbox>
		</view>
		<u-select v-model="areaPicker.show" mode="single-column" :list="areaPicker.list" @confirm="changeAreaCode"></u-select>
	</view>
</template>

<script>
	import {toast,goback,delay,jumpTo} from "@/utils/util.js"
	import {mapActions} from 'vuex'
	import areaCodes from "@/utils/areaCodes.js"
	import { accountLogin, getImageCode } from "@/api/user"
	export default {
		data() {
			return {
				areaCode:'86',
				phone:'',
				areaPicker:{
					show:false,
					list:areaCodes.map(({name,code})=>({label:`${name} ﹢${code}`,value:code}))
				},
				phoneStatus:{
					valid:false,
					error:false,
					des:''
				},
				imgStatus: {
					error: false,
					des: ''
				},
				password:'',
				pwdStatus:{
					error: false,
					des: ''
				},
				captcha:{ 
					token:'', 
					base64:'', 
					code:'' 
				},
				agree:false,
				lock:false
			}
		},
		onLoad() {
			this.getCaptcha()
		},
		methods: {
			jumpTo,
			...mapActions('user',['login']),
			async getCaptcha() {
				const {
					imageBase64,
					token
				} = await getImageCode();
				this.captcha.base64 = imageBase64
				this.captcha.token = token;
			},
			async checkAgree() {
				if (!this.agree) {
					// #ifdef APP-PLUS
					uni.vibrateShort()
					// #endif
					throw toast('请勾选同意协议')
				}
			},
			async checkPhone(){
				if(!this.phone){
					this.phoneStatus.error=true
					this.phoneStatus.des = '请输入手机号'
					this.phoneStatus.valid=false
					throw new Error('请输入手机号')
				}
				
				
				
				
				
				
				this.phoneStatus.error=false
				this.phoneStatus.des = ''
				this.phoneStatus.valid=true;
				return true;
			},
			async checkPwd(){
				if(!this.password){
					this.pwdStatus.error = true;
					this.pwdStatus.des = '请输入登录密码'
					throw new Error('请输入登录密码')
				}
				this.pwdStatus.error = false;
				this.pwdStatus.des = ''
				return true;
			},
			async checkCaptcha() {
				if(!this.captcha.code){
					this.imgStatus.error = true;
					this.imgStatus.des = '请输入图形码'
					throw new Error('请输入图形码')
				}
				this.imgStatus.error = false;
				this.imgStatus.des = ''
				return true;
			},
			changeAreaCode([{value}]){
				this.areaCode = value
			},
			async submit(){
				if(this.lock){
					throw new Error('正在请求中')
				}
				try {
					await this.checkAgree();
					await Promise.all([this.checkPhone(),this.checkPwd(),this.checkCaptcha()]) 
				} catch (e) {
					return
				}
				
				try{
					this.lock = true
					const phone = await this.handlePhone()
					const mobile = `${this.areaCode=='86'?'':'+'+this.areaCode}${phone}`
					
					const {
						token,
						userInfo,
						isNewUser
					} = await accountLogin({
						userNum:mobile,
						pwd:this.password,
						verCode:this.captcha.code,
						verToken:this.captcha.token
					})
					if(/default_head.jpeg$/.test(userInfo.avatarUrl)){
                        console.log(userInfo.avatarUrl)
						const {userName,avatarUrl} = await this.improveAvatar(token)
						console.log(userName,avatarUrl)
						userInfo.avatarUrl = avatarUrl
						userInfo.userName = userName
						await delay(500)
					}
					
					
					
					
					
					await this.login({
						token,
						userInfo
					})
					uni.showToast({
						title: '登录成功',
						duration: 1000
					});
					await delay(1000)
					goback(2)
				}catch(e){
					this.captcha.code = ''
					this.getCaptcha()
					toast(e.message||e.retDesc||'登录失败')
					await delay(1000)
				}finally{
					this.lock = false
				}
			},
			handlePhone(){
				return new Promise((resolve,reject)=>{
					var phone = this.phone;
					if (phone.charAt(0) === '0') {
						phone = phone.substring(1);
					}
					resolve(phone);
				})
			},
			improveAvatar(token){
				return new Promise((resolve,reject)=>{
					uni.navigateTo({
						url:`/pages/improve/avatar?token=${token}`,
						events:{
							successful:resolve
						},
						fail:reject,
						success(){
							
						}
					})
				})
			},
			improvePwd(token){
				return new Promise((resolve,reject)=>{
					uni.navigateTo({
						url:`/pages/improve/password?token=${token}`,
						events:{
							successful:resolve
						},
						fail:reject,
						success(){
							
						}
					})
				})
			},
			improvePhone(token){
				return new Promise((resolve,reject)=>{
					uni.navigateTo({
						url:`/pages/improve/phone?token=${token}`,
						events:{
							successful:resolve
						},
						fail:reject,
						success(){
							
						}
					})
				})
			}
		}
	}
</script>
<style>
	page{
		background-color: #ffffff;
	}
</style>
<style lang="scss" scoped>
	$error-color:#ff0000;
	.body{
		width: 600rpx;
		margin: 80rpx auto 0;
		.title {
			margin-bottom: 100rpx;
		}
		.img-code {
			flex: 0;
			min-width: 140rpx;
			height: 70rpx;
			background-size: auto 100%;
			background-repeat: no-repeat;
		}
		.input {
			text-align: left;
			margin-bottom: 10rpx;
			padding-bottom: 6rpx;
			font-size: 40rpx;
		}
		.tips {
			color: transparent;
			margin-bottom: 60rpx;
			margin-top: 8rpx;
			font-size: 20rpx;
		
			&.error {
				color: $error-color
			}
		}
		.submit {
			background-color: #436bed;
			color: #ffffff;
			border: none;
			font-size: 32rpx;
			padding: 28rpx 0;
			text-align: center;
			border-radius: 10rpx;
		
			&.disable {
				background-color: lighten($color: #436bed,$amount:20);
			}
		}
	}
</style>
